<!--
 * @Author: 汪军 624473119@qq.com
 * @Date: 2023-10-10 17:15:11
 * @LastEditors: 汪军 624473119@qq.com
 * @LastEditTime: 2023-12-12 09:41:41
 * @FilePath: \ekee-web\src\views\end\account-setting\AccountSetting.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div class="address-manage relative h100">
    <div class="container overflow-y">
      <EnterpriseCenterTitle :titleList="titleList"></EnterpriseCenterTitle>
      <div class="mt4 px4"></div>
      <!-- 新增收获地址 -->
      <div class="manage_detail">
        <div class="manage_from">
          <el-button
            type="primary"
            icon="plus"
            class="el_btn"
            @click="AddAddressDetail"
            >新增收货地址</el-button
          >
          <!-- 配送地址 -->
          <div class="manage_checkout">
            <div class="manage_where">当前配送至</div>
            <div class="mansge_contury">
              <el-select
                v-model="ruleForm.area"
                class="m-2 el_select"
                placeholder="请选择配送地址"
                style="border: none"
                @change="areaChange"
              >
                <el-option
                  v-for="item in options"
                  :key="item.label"
                  :label="item.label"
                  :value="item.label"
                />
              </el-select>
            </div>
          </div>
          <el-form
            ref="ruleFormRef"
            :model="ruleForm"
            :rules="rules"
            label-width="120px"
            class="demo-ruleForm"
            :size="formSize"
            status-icon
          >
            <el-row :gutter="10">
              <el-col :span="23">
                <el-form-item label="地址信息：" prop="address_ids">
                  <el-cascader
                    v-model="ruleForm.address_ids"
                    :options="areaData"
                    :props="props"
                    expandTrigger="hover"
                    @change="handleChange"
                    placeholder="请选择省/市/区/街道"
                    style="width: 100%"
                    ref="cascaderAddr"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="10">
              <el-col :span="23">
                <el-form-item label="详细地址：" prop="address">
                  <el-input
                    v-model="ruleForm.address"
                    minlength="5"
                    maxlength="30"
                    type="textarea"
                    :rows="3"
                    placeholder="请输入详细地址信息，如道路、门牌号、小区、楼栋号、单元等信息"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="10">
              <el-col :span="23">
                <el-form-item label="邮政编码：" prop="zip_code">
                  <el-input
                    v-model="ruleForm.zip_code"
                    maxlength="6"
                    placeholder="请填写邮箱"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="10">
              <el-col :span="23">
                <el-form-item label="收货人姓名：" prop="recipient">
                  <el-input
                    v-model="ruleForm.recipient"
                    placeholder="长度不超过25个字符"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="8">
              <el-form-item label="手机号码：" prop="mobile">
                <el-col :span="10">
                  <el-select
                    v-model="ruleForm.mobile_area_code"
                    class="m-2 el_select"
                    placeholder="请选择区号"
                    style="border: none"
                    @change="phoneNumberType"
                  >
                    <el-option
                      v-for="item in phoneNumberList"
                      :key="item.label"
                      :label="item.label"
                      :value="item.label"
                    />
                  </el-select>
                </el-col>
                <el-col :span="14">
                  <el-input v-model="ruleForm.mobile" maxlength="11" />
                </el-col>
              </el-form-item>
            </el-row>
            <el-row :gutter="10">
              <el-col :span="23">
                <el-form-item label="" prop="is_default">
                  <el-checkbox
                    v-model="ruleForm.is_default"
                    label="设置为默认收货地址"
                    size="large"
                    :true-label="2"
                    :false-label="1"
                    @change="isDefault"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item>
              <el-button
                type="primary"
                style="
                  width: 140px;
                  height: 42px;
                  background: #2487e8;
                  border-radius: 8px 8px 8px 8px;
                  opacity: 1;
                "
                @click="submitForm(ruleFormRef)"
              >
                保存
              </el-button>
              <!-- <el-button @click="resetForm(ruleFormRef)">Reset</el-button> -->
            </el-form-item>
          </el-form>
        </div>
      </div>
      <!-- 地址 -->
      <div class="manage_table">
        <el-table
          :data="tableData"
          style="width: 100%"
          border
          :header-cell-style="tableHeaderStyle"
          :cell-style="tableCellStyle"
          empty-text="暂无数据"
        >
          <el-table-column prop="recipient" label="收货人" width="120" />

          <el-table-column label="所在地区" width="180">
            <template #default="scope">
              <span
                >{{ scope.row.province }} {{ scope.row.city }}
                {{ scope.row.county }}</span
              >
            </template>
          </el-table-column>

          <el-table-column prop="address" label="详细地址" width="180" />
          <el-table-column prop="zip_code" label="邮编" width="120" />
          <el-table-column prop="mobile" label="手机号" width="120" />
          <el-table-column label="操作">
            <template #default="scope">
              <el-button
                size="small"
                @click="handleEdit(scope.$index, scope.row)"
                >编辑</el-button
              >
              <el-button
                size="small"
                type="danger"
                @click="handleDelete(scope.$index, scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
          <el-table-column label="默认" width="100">
            <template #default="scope">
              <span v-if="scope.row.is_default == 2">默认地址</span>
              <span
                style="cursor: pointer"
                v-if="scope.row.is_default == 1"
                @click="setDefault(scope.row)"
                >设为默认</span
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <!-- 分页 -->
    <TablePagination
      v-if="totalList > 0"
      :totalList="totalList"
      :page="addressPage.page"
      @handleCurrentChange="handleCurrentChange"
    ></TablePagination>
  </div>
</template>


<script setup>
import { computed, onMounted, ref } from "vue";
import EnterpriseCenterTitle from "@/components/EnterpriseCenterTitle.vue";
import TablePagination from "@/components/TablePagination.vue";
import {
  AddressIndex,
  AddressSave,
  AddressDelete,
  AddressSetdefault,
} from "@/api/address";
import { Category, Area } from "@/api/common.js";

// 引入地址
// import areaData from "@/utils/citysList.js";
const count = ref(0);

onMounted(() => {
  getAddressIndex();
  getArea();
});

//省市区列表
const areaData = ref([]);
//获取省市区
const getArea = () => {
  Area()
    .then((res) => {
      if (res.code == 1) {
        areaData.value = res.data;
      }
    })
    .catch((err) => {});
};

//获取列表
const addressPage = ref({
  page: 1,
  page_size: 10,
});
const getAddressIndex = () => {
  AddressIndex(addressPage.value).then((res) => {
    if (res.code == 1) {
      console.log("redscds", res.data.data);
      tableData.value = res.data.data;
      totalList.value = res.data.total;
    }
  });
};
// const areaTree = ref([]);
// areaTree.value = areaData.regionData;
//地址
const props = {
  expandTrigger: "hover",
  label: "name",
  value: "id",
  children: "children",
};
//获取节点
const cascaderAddr = ref(null);
const handleChange = (e, form, thsAreaCode, value) => {
  if (cascaderAddr.value.getCheckedNodes()[0] != undefined) {
    thsAreaCode = cascaderAddr.value.getCheckedNodes()[0].pathLabels; // 注意2： 获取label值
    ruleForm.value.province = thsAreaCode[0];
    ruleForm.value.city = thsAreaCode[1];
    ruleForm.value.county = thsAreaCode[2];

    console.log("from", ruleForm); // 注意3： 最终结果是个一维数组对象
  } else {
    // this.searchfrom.area = ''
    ruleForm.value.province = "";
    ruleForm.value.city = "";
    ruleForm.value.county = "";
  }
};
const titleList = ref([
  {
    name: "地址管理",
    value: "",
  },
]);
//切换地区
const value = ref("");
const options = ref([
  {
    value: "1",
    label: "中国香港",
  },
  {
    value: "2",
    label: "中国澳门",
  },
  {
    value: "3",
    label: "中国台湾",
  },
]);
const formSize = ref("default");
const ruleFormRef = ref();

const ruleForm = ref({
  zip_code: "", //邮政编码
  recipient: "", //收件人
  mobile: "", //收件人电话
  is_default: 1, //是否默认
  province: "", //省
  city: "", //市
  county: "", //区
  address: "", //详细地址
  address_ids: [],
  mobile_area_code: "", //国家区号选择、
  id: "", //编辑的时候传 新增不传
  area: "", //地区选择
});
//手机号码
const validatorUsername = (rule, value, callback) => {
  if (!/^1(3[0-9]|5[0-3,5-9]|7[1-3,5-8]|8[0-9])\d{8}$/.test(value))
    return callback(new Error("请输入正确格式的手机号！"));
  callback();
};
//手机号切换
const phoneNumberList = ref([
  {
    value: "1",
    label: "中国大陆 +86",
  },
  {
    value: "2",
    label: "中国香港 +852",
  },
  {
    value: "3",
    label: "中国台湾 +886",
  },
  {
    value: "4",
    label: "中国澳门 +853",
  },
  {
    value: "5",
    label: "新加坡 +65",
  },
  {
    value: "6",
    label: "日本 +81",
  },
  {
    value: "7",
    label: "泰国 +66",
  },
  {
    value: "8",
    label: "马来西亚 +60",
  },
  {
    value: "9",
    label: "美国 +1",
  },
  {
    value: "10",
    label: "英国 +44",
  },
]);
const rules = ref({
  recipient: [
    { required: true, message: "请输入收货人姓名", trigger: "blur" },
    { min: 1, max: 25, message: "收货人姓名长度不超过25个字", trigger: "blur" },
  ],
  address_ids: [
    {
      required: true,
      message: "请选择省/市/区/街道",
      trigger: "blur",
    },
  ],
  address: [
    {
      required: true,
      message: "请输入详细地址信息，如道路、门牌号、小区、楼栋号、单元等信息",
      trigger: "blur",
    },
  ],
  mobile: [
    { required: true, message: "手机号不能为空", trigger: "blur" },

    // validator - 自定义校验规则
    { validator: validatorUsername, trigger: "blur" },
  ],
});
//配送地址
const areaChange = (val) => {
  ruleForm.value.area = val;
};
//不同国家号码切换
const phoneNumberType = (val) => {
  ruleForm.value.mobile_area_code = val;
};
//是否默认
const isDefault = (val) => {
  ruleForm.value.is_default = val;
  console.log("val", val);
};
//保存新增
const submitForm = async (formEl) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      ruleForm.value.address_ids = ruleForm.value.address_ids.join(",");
      AddressSave(ruleForm.value)
        .then((res) => {
          if (res.code == 1) {
            ElMessage({ message: res.msg, type: "success" });
            formEl.resetFields();
            ruleForm.value.mobile_area_code = "";
            ruleForm.value.area = "";
            getAddressIndex();
          } else {
            ElMessage({ message: res.msg, type: "error" });
          }
        })
        .catch((err) => {});
    } else {
      console.log("error submit!", fields);
    }
  });
};

//删除地址
const handleDelete = (val, row) => {
  console.log("eeews", row.id);
  AddressDelete({ id: row.id }).then((res) => {
    if (res.code == 1) {
      ElMessage({ message: res.msg, type: "success" });
      getAddressIndex();
    } else {
      ElMessage({ message: res.msg, type: "error" });
    }
  });
};

//设置默认
const setDefault = (row) => {
  AddressSetdefault({ id: row.id })
    .then((res) => {
      if (res.code == 1) {
        ElMessage({ message: res.msg, type: "success" });
        getAddressIndex();
      } else {
        ElMessage({ message: res.msg, type: "error" });
      }
    })
    .catch((err) => {});
};

const tableHeaderStyle = ref({
  backgroundColor: "#E5E6EB",
  color: "#000000",
  textAlign: "center",
});
const tableCellStyle = ref({
  textAlign: "center",
});
const tableData = ref([]);
//编辑当前地址
const handleEdit = (indexInfo, row) => {
  console.log("编辑回显", indexInfo, row);
  ruleForm.value = row;

  ruleForm.value.address_ids = row.address_ids.split(",").map(Number);
  // tregionList.value = row.province;
};
//新增收获地址
const AddAddressDetail = () => {};

const resetForm = (formEl) => {
  if (!formEl) return;
  formEl.resetFields();
};

// 数据总条数
const totalList = ref(0);
const handleCurrentChange = (val) => {
  addressPage.value.page = val;
  getAddressIndex();
};
</script>

<style lang="less" scoped>
.enterprise-center {
  color: #888;
}
.manage_table {
  padding: 16px;
}
.address-manage {
  // display: flex;
  // border: 1px solid red;
  box-sizing: border-box;
  .container {
    height: calc(100vh - 204px);
  }
  .manage_detail {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    .manage_from {
      width: 530px;
      // border: 1px solid red;
      margin: 22px 0;
      .el_btn {
        width: 142px;
        height: 40px;
        background: #2487e8;
        border-radius: 4px 4px 4px 4px;
        opacity: 1;
      }
      .manage_checkout {
        box-sizing: border-box;
        padding: 12px;
        width: 510px;
        height: 46px;
        background: #f5f5f5;
        border-radius: 8px 8px 8px 8px;
        opacity: 1;
        margin: 18px 0;
        display: flex;
        align-items: center;
        // justify-content: space-between;
        .manage_where {
          width: 70px;
          font-size: 14px;
          font-family: PingFang SC-Medium, PingFang SC;
          font-weight: 500;
          color: rgba(0, 0, 0, 0.6);
        }
        .mansge_contury {
          flex: 1;
          .el_select {
            width: 97%;
            padding-left: 15px;
            border: none;
          }
        }
      }
    }
  }
}
</style>
